package com.example.mvvmdemo.ui.viewmodel;

import com.example.mvvmdemo.domain.usecase.MainUseCase;
import com.example.mvvmdemo.domain.ApiErrorExcepton;
import com.example.mvvmdemo.ui.model.TestModelVm;
import com.example.mvvmdemo.ui.model.ToastVm;

import android.databinding.ObservableField;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.subjects.PublishSubject;

public class MainViewMode extends ViewModel {

    private final MainUseCase mainUseCase;

    public final ObservableField<String> successText;

    public final ObservableField<Float> btn1ColorField;

    private final PublishSubject<String> jumpSubject;

    @Inject
    protected MainViewMode(MainUseCase mainUseCase) {
        super(mainUseCase);
        this.mainUseCase = mainUseCase;
        successText = new ObservableField<>();
        btn1ColorField = new ObservableField<>();
        btn1ColorField.set(0.5f);
        jumpSubject = PublishSubject.create();
    }

    public Observable<String> getJumpObservable() {
        return jumpSubject.hide();
    }

    public void success() {
        successText.set("");
        assert mainUseCase != null;
        mainUseCase.execute(new DisposableObserver<List<TestModelVm>>() {
            @Override
            public void onNext(List<TestModelVm> testModelVms) {

                if (!testModelVms.isEmpty()) {
                    TestModelVm testModelVm = testModelVms.get(0);
                    successText.set(
                        testModelVm.getCode() + " " + testModelVm.getId() + " " + testModelVm
                            .getName());
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        }, mainUseCase.testApi());
    }

    public void onBtn1Click() {
        success();
    }

    public void onBtn2Click() {
        error();
    }

    public void onBtn3Click() {
        jumpSubject.onNext("");
    }

    private void error() {
        successText.set("");
        mainUseCase.execute(new DisposableObserver<List>() {
            @Override
            public void onNext(List testModels) {
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof ApiErrorExcepton) {
                    toastSubject.onNext(new ToastVm(((ApiErrorExcepton) e).getCode(),
                        ((ApiErrorExcepton) e).getMsg()));
                }
            }

            @Override
            public void onComplete() {

            }
        }, mainUseCase.testErrorApi());
    }
}
